import router from '@/router'
import auth from '@/api/auth'
import utils from '@/utils/utils'
import smsApi from '@/api/msm'

// 注册表单数据信息
const registerForm = {
  phone: '',
  trueName: '',
  password: '',
  code: '',
  sending: true,      // 是否可以发送验证码
  second: -1,        // 倒计时间  second>0 : 显示倒计时 second=0 ：重新发送 second=-1 ：什么都不显示
  clearSmsTime: null  // 倒计时定时任务引用 关闭登录层清除定时任务
}
// 自定义用户名校验规则
const validatePhone = (rule, value, callback) => {
  auth.checkPhone(registerForm.phone)
    .then(resp => {
      if (resp.data) {
        callback()
      } else {
        callback(new Error('该手机号已注册'))
      }
    })
}
// 登录表单的校验规则
const registerFormRules = {
  phone: [
    {
      required: true,
      message: '请输入手机号',
      trigger: 'blur'
    },
    {
      validator: validatePhone,
      trigger: 'blur'
    }
  ],
  trueName: [
    {
      required: true,
      message: '请输入您的姓名',
      trigger: 'blur'
    },
  ],
  password: [
    {
      required: true,
      message: '请输入密码',
      trigger: 'blur'
    },
    {
      min: 5,
      message: '密码不能小于5个字符',
      trigger: 'blur'
    }
  ],
  code: [
    {
      required: true,
      message: '请输入验证码',
      trigger: 'blur'
    }
  ],
}

const toLoginPage = () => {
  router.push('/')
}

const getCodeFun = (formEl) => {
  if (!(/^1[34578]\d{9}$/.test(registerForm.phone))) {
    formEl.$message.error('手机号码不正确')
    return;
  }
  // // 控制重复发送
  // if (!this.registerForm.sending) return;
  if(registerForm.clearSmsTime) {
    clearInterval(registerForm.clearSmsTime);
  }
  registerForm.second = 60;

  //this.registerForm.labelTips = '验证码已发送至' + this.userInfo.phone
  registerForm.clearSmsTime = setInterval(() => {
    --registerForm.second;
    if (registerForm.second < 1) {
      clearInterval(registerForm.clearSmsTime);
      registerForm.sending = true;
      registerForm.second = 0;
    }
  }, 1000);
  // 发送短信验证码
  registerForm.sending = false;
  smsApi.sendCode(registerForm.phone).then(response => {
  }).catch(e => {
    formEl.$message.error('发送失败，重新发送')
  })
}
// 表单信息提交
const register = (formEl) => {
  utils.validFormAndInvoke(formEl, () => {
    auth.register(registerForm).then(resp => {
      if (resp.code === 200) {
        localStorage.setItem('authorization', resp.data)
        router.push('/index')
      }
    })
  }, '注册失败')
}

export default {
  // data
  registerForm,
  registerFormRules,
  // method
  toLoginPage,
  getCodeFun,
  register,
}
